<template>
  <div class="sales-order-container">
    <!-- 销售订单主表 -->
    <div class="sales-order-section">
      <div class="section-header">
        <h3>销售订单</h3>
      </div>
      
      <!-- 搜索和操作栏 -->
      <div class="search-action-bar">
        <div class="search-area">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="单据编号"
            clearable
          />
          <el-button type="primary" @click="handleSearch">Q查询</el-button>
        </div>
        
        <div class="action-buttons">
          <el-button type="success" @click="handleAdd">+新建</el-button>
          <el-button type="primary" @click="handleEdit" :disabled="!selectedRows.length">编辑</el-button>
          <el-button type="warning" @click="handlePrint" :disabled="!selectedRows.length">打印</el-button>
          <el-button type="warning" @click="handleExportTemplate">模版Excel导出</el-button>
          <el-button type="danger" @click="handleDelete" :disabled="!selectedRows.length">删除</el-button>
          <el-button type="success" @click="handleExport">↓导出</el-button>
          <el-button type="info" @click="handleColumnSettings">
            <el-icon><Grid /></el-icon>
          </el-button>
        </div>
      </div>

                            <!-- 销售订单表格 -->
        <div class="table-container">
          <el-table
            :data="salesOrderList"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            v-loading="loading"
            style="width: 100%"
            border
            stripe
            highlight-current-row
          >
            <el-table-column type="index" width="60" align="center" />
            <el-table-column type="selection" width="50" />
            <el-table-column 
              v-for="column in visibleColumns" 
              :key="column.prop"
              :prop="column.prop" 
              :label="column.label" 
              :sortable="column.sortable"
              :width="column.width"
            >
              <template #default="scope" v-if="column.prop === 'createTime' || column.prop === 'modifyTime'">
                {{ formatDateTime(scope.row[column.prop]) }}
              </template>
            </el-table-column>
          </el-table>
        </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 销售订单产品明细 -->
    <div class="product-detail-section">
             <div class="section-header">
         <h3>销售订单-产品明细 {{ currentSalesOrderId ? `(订单ID: ${currentSalesOrderId})` : '(全部产品明细)' }}</h3>
         <div class="section-actions">
           <el-button type="info" size="small" @click="handleShowAllProducts">显示全部</el-button>
         </div>
       </div>
      
                            <!-- 产品明细表格 -->
        <div class="table-container">
          <el-table
            :data="productDetailList"
            @selection-change="handleProductSelectionChange"
            v-loading="productLoading"
            style="width: 100%"
            border
            stripe
          >
            <el-table-column type="index" width="60" align="center" />
            <el-table-column type="selection" width="50" />
            <el-table-column prop="productCode" label="*产品编号" sortable width="220" />
            <el-table-column prop="productName" label="*产品名称" sortable width="180" />
            <el-table-column prop="productSpec" label="产品规格" width="150" />
            <el-table-column prop="workOrderNo" label="工单编号" width="220" />
            <el-table-column prop="quantity" label="*数量" sortable width="100" />
            <el-table-column prop="completedQty" label="完成数" width="100" />
            <el-table-column prop="createTime" label="创建时间" sortable width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="creator" label="创建人" width="120" />
            <el-table-column prop="modifier" label="修改人" width="120" />
            <el-table-column prop="modifyTime" label="修改时间" sortable width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.modifyTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
    </div>

    <!-- 销售订单新建弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="① 销售订单(新建)"
      width="90%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="sales-order-dialog"
    >
      <div class="dialog-content">
        <!-- 销售订单信息 -->
        <div class="order-info-section">
          <div class="form-row">
            <div class="form-item">
              <label>单据编号:</label>
              <el-input
                v-model="newOrderForm.orderNo"
                placeholder="请输入,忽略将自动生成"
                clearable
              />
            </div>
            <div class="form-item">
              <label>备注:</label>
              <el-input
                v-model="newOrderForm.remark"
                type="textarea"
                :rows="3"
                placeholder="备注"
                clearable
              />
            </div>
          </div>
        </div>

        <!-- 提示信息 -->
        <div class="hint-banner">
          <el-icon><Warning /></el-icon>
          <span>点击【数量】可以对订单数量直接进行修改</span>
        </div>

        <!-- 产品明细 -->
        <div class="product-detail-section">
          <div class="section-header">
            <h3>■ 销售订单-产品明细</h3>
            <div class="section-actions">
              <el-button type="primary" size="small" @click="handleSelectProduct">+选择产品</el-button>
              <el-button type="danger" size="small" @click="handleDeleteProductRow" :disabled="!selectedProductRows.length">删除行</el-button>
              <el-button type="warning" size="small" @click="handleImportProduct">
                <el-icon><Upload /></el-icon>
                导入
              </el-button>
              <el-button type="info" size="small" @click="handleRefreshProduct">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
          
          <!-- 产品明细表格 -->
          <div class="table-container">
            <el-table
              :data="newOrderProductList"
              @selection-change="handleNewOrderProductSelectionChange"
              v-loading="newOrderProductLoading"
              style="width: 100%"
              border
              stripe
            >
              <el-table-column type="selection" width="50" />
              <el-table-column prop="productCode" label="*产品编号" sortable width="220" />
              <el-table-column prop="productName" label="*产品名称" sortable width="180" />
              <el-table-column prop="productSpec" label="产品规格" width="150" />
              <el-table-column prop="workOrderNo" label="工单编号" width="220" />
              <el-table-column prop="quantity" label="*数量" sortable width="100">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.quantity"
                    type="number"
                    size="small"
                    placeholder="数量"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="completedQty" label="完成数" width="100" />
              <el-table-column prop="createTime" label="创建时间" sortable width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="creator" label="创建人" width="120" />
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              :current-page="newOrderPagination.pageIndex"
              :page-size="newOrderPagination.pageSize"
              :page-sizes="[10, 20, 30, 50, 100]"
              :total="newOrderPagination.totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleNewOrderSizeChange"
              @current-change="handleNewOrderCurrentChange"
            />
          </div>
        </div>
      </div>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSaveOrder">
            <el-icon><Check /></el-icon>
            保存
          </el-button>
          <el-button @click="handleCloseDialog">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
        </div>
             </template>
     </el-dialog>

     <!-- 产品选择弹窗 -->
     <el-dialog
       v-model="productSelectDialogVisible"
       title="选择产品"
       width="80%"
       :close-on-click-modal="false"
       :close-on-press-escape="false"
       class="product-select-dialog"
     >
       <div class="dialog-content">
         <!-- 搜索区域 -->
         <div class="search-section">
           <div class="search-row">
             <div class="search-item">
               <label>产品编号:</label>
               <el-input
                 v-model="productSearchForm.productCode"
                 placeholder="请输入产品编号"
                 clearable
               />
             </div>
             <div class="search-item">
               <label>产品名称:</label>
               <el-input
                 v-model="productSearchForm.productName"
                 placeholder="请输入产品名称"
                 clearable
               />
             </div>
             <div class="search-item">
               <label>产品规格:</label>
               <el-input
                 v-model="productSearchForm.productSpec"
                 placeholder="请输入产品规格"
                 clearable
               />
             </div>
             <div class="search-item">
               <el-button type="primary" @click="handleProductSearch">查询</el-button>
               <el-button @click="handleProductSearchReset">重置</el-button>
             </div>
           </div>
         </div>

         <!-- 产品列表表格 -->
         <div class="product-table-section">
           <el-table
             :data="productSelectList"
             @selection-change="handleProductSelectChange"
             v-loading="productSelectLoading"
             style="width: 100%"
             border
             stripe
             height="400"
           >
             <el-table-column type="selection" width="50" />
             <el-table-column prop="productCode" label="产品编号" sortable width="200" />
             <el-table-column prop="productName" label="产品名称" sortable width="200" />
             <el-table-column prop="productSpec" label="产品规格" width="150" />
             <el-table-column prop="unit" label="库存单位" width="100" />
             <el-table-column prop="stockQty" label="库存数量" sortable width="120" />
             <el-table-column prop="price" label="单价" sortable width="120" />
             <el-table-column prop="createTime" label="创建时间" sortable width="180">
               <template #default="scope">
                 {{ formatDateTime(scope.row.createTime) }}
               </template>
             </el-table-column>
           </el-table>
         </div>

         <!-- 分页 -->
         <div class="pagination-container">
           <el-pagination
             :current-page="productSelectPagination.pageIndex"
             :page-size="productSelectPagination.pageSize"
             :page-sizes="[10, 20, 30, 50, 100]"
             :total="productSelectPagination.totalCount"
             layout="total, sizes, prev, pager, next, jumper"
             @size-change="handleProductSelectSizeChange"
             @current-change="handleProductSelectCurrentChange"
           />
         </div>
       </div>

       <!-- 弹窗底部按钮 -->
       <template #footer>
         <div class="dialog-footer">
           <el-button type="primary" @click="handleConfirmProductSelect" :disabled="!selectedProductSelectRows.length">
             确定选择
           </el-button>
           <el-button @click="handleCloseProductSelectDialog">
             取消
           </el-button>
         </div>
       </template>
     </el-dialog>

     <!-- 销售订单编辑弹窗 -->
     <el-dialog
       v-model="editDialogVisible"
       title="① 销售订单(编辑)"
       width="90%"
       :close-on-click-modal="false"
       :close-on-press-escape="false"
       class="sales-order-dialog"
     >
       <div class="dialog-content">
         <!-- 销售订单信息 -->
         <div class="order-info-section">
           <div class="form-row">
             <div class="form-item">
               <label>单据编号:</label>
               <el-input
                 v-model="editOrderForm.orderNo"
                 placeholder="单据编号"
                 disabled
               />
             </div>
             <div class="form-item">
               <label>备注:</label>
               <el-input
                 v-model="editOrderForm.remark"
                 type="textarea"
                 :rows="3"
                 placeholder="备注"
                 clearable
               />
             </div>
           </div>
         </div>

         <!-- 提示信息 -->
         <div class="hint-banner">
           <el-icon><Warning /></el-icon>
           <span>点击【数量】可以对订单数量直接进行修改</span>
         </div>

         <!-- 产品明细 -->
         <div class="product-detail-section">
           <div class="section-header">
             <h3>■ 销售订单-产品明细</h3>
             <div class="section-actions">
               <el-button type="primary" size="small" @click="handleEditSelectProduct">+选择产品</el-button>
               <el-button type="danger" size="small" @click="handleEditDeleteProductRow" :disabled="!selectedEditOrderProductRows.length">删除行</el-button>
               <el-button type="warning" size="small" @click="handleEditImportProduct">
                 <el-icon><Upload /></el-icon>
                 导入
               </el-button>
               <el-button type="info" size="small" @click="handleEditRefreshProduct">
                 <el-icon><Refresh /></el-icon>
                 刷新
               </el-button>
             </div>
           </div>
           
           <!-- 产品明细表格 -->
           <div class="table-container">
             <el-table
               :data="editOrderProductList"
               @selection-change="handleEditOrderProductSelectionChange"
               v-loading="editOrderProductLoading"
               style="width: 100%"
               border
               stripe
             >
               <el-table-column type="selection" width="50" />
               <el-table-column prop="productCode" label="*产品编号" sortable width="220" />
               <el-table-column prop="productName" label="*产品名称" sortable width="180" />
               <el-table-column prop="productSpec" label="产品规格" width="150" />
               <el-table-column prop="workOrderNo" label="工单编号" width="220" />
               <el-table-column prop="quantity" label="*数量" sortable width="100">
                 <template #default="scope">
                   <el-input
                     v-model="scope.row.quantity"
                     type="number"
                     size="small"
                     placeholder="数量"
                   />
                 </template>
               </el-table-column>
               <el-table-column prop="completedQty" label="完成数" width="100" />
               <el-table-column prop="createTime" label="创建时间" sortable width="180">
                 <template #default="scope">
                   {{ formatDateTime(scope.row.createTime) }}
                 </template>
               </el-table-column>
               <el-table-column prop="creator" label="创建人" width="120" />
             </el-table>
           </div>

           <!-- 分页 -->
           <div class="pagination-container">
             <el-pagination
               :current-page="editOrderPagination.pageIndex"
               :page-size="editOrderPagination.pageSize"
               :page-sizes="[10, 20, 30, 50, 100]"
               :total="editOrderPagination.totalCount"
               layout="total, sizes, prev, pager, next, jumper"
               @size-change="handleEditOrderSizeChange"
               @current-change="handleEditOrderCurrentChange"
             />
           </div>
         </div>
       </div>

       <!-- 弹窗底部按钮 -->
       <template #footer>
         <div class="dialog-footer">
           <el-button type="success" @click="handleSaveEditOrder">
             <el-icon><Check /></el-icon>
             保存
           </el-button>
           <el-button @click="handleCloseEditDialog">
             <el-icon><Close /></el-icon>
             关闭
           </el-button>
         </div>
       </template>
     </el-dialog>

     <!-- 列设置弹窗 -->
     <el-dialog
       v-model="columnSettingsVisible"
       title="设置"
       width="500px"
       :close-on-click-modal="false"
       :close-on-press-escape="false"
       class="column-settings-dialog"
     >
       <div class="column-settings-content">
         <!-- 提示信息 -->
         <div class="settings-hint">
           <el-icon><Warning /></el-icon>
           <span>拖动列名可调整表格列显示顺序</span>
         </div>
         
         <!-- 列配置表格 -->
         <div class="column-config-table">
           <div class="column-list">
             <div 
               v-for="(column, index) in columnConfigList" 
               :key="column.prop"
               class="column-item"
               :data-index="index"
               draggable="true"
               @dragstart="handleDragStart(index)"
               @dragover.prevent
               @drop="handleDrop(index)"
               @dragenter.prevent
               @dragleave="handleDragLeave(index)"
               @dragenter="handleDragEnter(index)"
             >
               <div class="column-content">
                 <div class="column-index">{{ column.index }}</div>
                 <div class="column-name">
                   <el-icon class="drag-handle"><Grid /></el-icon>
                   <span>{{ column.label }}</span>
                 </div>
                 <div class="column-visible">
                   <el-checkbox
                     v-model="column.visible"
                     @change="handleColumnVisibilityChange"
                   />
                 </div>
               </div>
             </div>
           </div>
         </div>
       </div>

       <!-- 弹窗底部按钮 -->
       <template #footer>
         <div class="dialog-footer">
           <el-button @click="handleCloseColumnSettings">
             <el-icon><Close /></el-icon>
             ×取消
           </el-button>
           <el-button type="success" @click="handleResetColumnSettings">
             <el-icon><Refresh /></el-icon>
             重置
           </el-button>
           <el-button type="primary" @click="handleConfirmColumnSettings">
             <el-icon><Check /></el-icon>
             √确定
           </el-button>
         </div>
       </template>
     </el-dialog>

     <!-- 打印预览弹窗 -->
     <el-dialog
       v-model="printDialogVisible"
       title="打印预览 - 销售订单明细"
       width="90%"
       :close-on-click-modal="false"
       :close-on-press-escape="false"
       class="print-preview-dialog"
     >
       <div class="print-preview-content">
         <!-- 打印预览头部 -->
         <div class="print-header">
           <div class="company-logo">
             <div class="logo-circle">IMES</div>
           </div>
           <div class="print-title">销售订单明细</div>
           <div class="qr-code">
             <div class="qr-placeholder">二维码</div>
           </div>
         </div>

         <!-- 订单信息 -->
         <div class="order-info" v-if="printData && printData.length > 0">
           <div v-for="(order, index) in printData" :key="index" class="order-section">
             <div class="order-header" v-if="printData.length > 1">
               <h4>销售订单 {{ index + 1 }}</h4>
             </div>
             <div class="info-row">
               <span class="info-label">单据编号:</span>
               <span class="info-value">{{ order.orderNo }}</span>
             </div>
             <div class="info-row">
               <span class="info-label">制单人:</span>
               <span class="info-value">{{ order.creator }}</span>
             </div>
             <div class="info-row">
               <span class="info-label">创建时间:</span>
               <span class="info-value">{{ formatDateTime(order.createTime) }}</span>
             </div>
             <div class="info-row" v-if="order.remark">
               <span class="info-label">备注:</span>
               <span class="info-value">{{ order.remark }}</span>
             </div>
             <div class="order-divider" v-if="index < printData.length - 1"></div>
           </div>
         </div>

         <!-- 产品明细表格 -->
         <div class="product-detail-table" v-if="printProductDetails.length > 0">
           <table class="print-table">
             <thead>
               <tr>
                 <th>产品编号</th>
                 <th>产品名称</th>
                 <th>产品规格</th>
                 <th>数量</th>
                 <th>完成数</th>
               </tr>
             </thead>
             <tbody>
               <tr v-for="(item, index) in printProductDetails" :key="index">
                 <td>{{ item.productCode }}</td>
                 <td>{{ item.productName }}</td>
                 <td>{{ item.productSpec || '-' }}</td>
                 <td>{{ item.quantity }}</td>
                 <td>{{ item.completedQty || 0 }}</td>
               </tr>
             </tbody>
           </table>
         </div>

         <!-- 打印说明 -->
         <div class="print-footer">
           <p>打印时间: {{ formatDateTime(new Date().toISOString()) }}</p>
         </div>
       </div>

       <!-- 弹窗底部按钮 -->
       <template #footer>
         <div class="dialog-footer">
           <el-button type="primary" @click="handlePrintPreview">
             <el-icon><Upload /></el-icon>
             打印预览
           </el-button>
           <el-button type="success" @click="handlePrintExecute">
             <el-icon><Upload /></el-icon>
             执行打印
           </el-button>
           <el-button @click="handleClosePrintDialog">
             <el-icon><Close /></el-icon>
             关闭
           </el-button>
         </div>
       </template>
     </el-dialog>

     <!-- 导入产品明细弹窗 -->
     <el-dialog
       v-model="importDialogVisible"
       title="销售订单-产品明细-导入"
       width="600px"
       :close-on-click-modal="false"
       class="import-dialog"
     >
       <div class="import-content">
         <!-- 操作按钮区域 -->
         <div class="import-actions">
           <el-button @click="handleSelectFile" :icon="Upload">
             选择文件
           </el-button>
           <el-button type="primary" @click="handleDownloadTemplate" :icon="Download">
             下载模板
           </el-button>
           <el-button type="success" @click="handleUploadFile" :icon="Upload" :disabled="!selectedFile">
             上传文件
           </el-button>
         </div>

         <!-- 上传说明 -->
         <div class="upload-notice">
           <el-icon><Warning /></el-icon>
           <div class="notice-content">
             <span class="notice-title">上传说明</span>
             <span class="notice-text">只能上传excel文件,文件大小不超过100M</span>
           </div>
         </div>

         <!-- 文件选择区域 -->
         <div class="file-drop-zone" @click="handleSelectFile" @drop="handleFileDrop" @dragover="handleFileDragOver" @dragleave="handleFileDragLeave">
           <div v-if="!selectedFile" class="drop-placeholder">
             <el-icon class="upload-icon"><Upload /></el-icon>
             <p>点击选择文件或拖拽文件到此处</p>
           </div>
           <div v-else class="selected-file">
             <el-icon class="file-icon"><Document /></el-icon>
             <span class="file-name">{{ selectedFile.name }}</span>
             <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
           </div>
         </div>
       </div>

       <template #footer>
         <span class="dialog-footer">
           <el-button @click="handleCloseImport">关闭</el-button>
         </span>
       </template>
     </el-dialog>
   </div>
 </template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Grid, Warning, Upload, Refresh, Check, Close, Download, Document } from '@element-plus/icons-vue'
import { MES_SMH_ApiHost } from '@/utils/Interceptors'

// 时间格式化函数
const formatDateTime = (dateTime: string | null | undefined) => {
  if (!dateTime) return ''
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) return dateTime
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
  } catch (error) {
    return dateTime
  }
}

// 响应式数据
const loading = ref(false)
const productLoading = ref(false)
const selectedRows = ref<any[]>([])
const selectedProductRows = ref<any[]>([])
const salesOrderList = ref<any[]>([])
const productDetailList = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  pageIndex: 1,
  pageSize: 30
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 30,
  totalCount: 0,
  totalPage: 0
})

// 当前选中的销售订单ID
const currentSalesOrderId = ref<number | null>(null)



// 弹窗相关数据
const dialogVisible = ref(false)
const newOrderForm = reactive({
  orderNo: '',
  remark: ''
})

// 新建订单产品明细相关数据
const newOrderProductList = ref<any[]>([])
const newOrderProductLoading = ref(false)
const selectedNewOrderProductRows = ref<any[]>([])

// 新建订单分页数据
const newOrderPagination = reactive({
  pageIndex: 1,
  pageSize: 100,
  totalCount: 0,
  totalPage: 0
})

// 产品选择弹窗相关数据
const productSelectDialogVisible = ref(false)
const productSearchForm = reactive({
  productCode: '',
  productName: '',
  productSpec: ''
})

// 产品选择列表相关数据
const productSelectList = ref<any[]>([])
const productSelectLoading = ref(false)
const selectedProductSelectRows = ref<any[]>([])

// 产品选择分页数据
const productSelectPagination = reactive({
  pageIndex: 1,
  pageSize: 20,
  totalCount: 0,
  totalPage: 0
})

// 导入相关数据
const importDialogVisible = ref(false)
const selectedFile = ref<File | null>(null)
const fileInputRef = ref<HTMLInputElement | null>(null)

// 编辑弹窗相关数据
const editDialogVisible = ref(false)
const editOrderForm = reactive({
  salesOrderId: null as number | null,
  orderNo: '',
  remark: ''
})

// 编辑订单产品明细相关数据
const editOrderProductList = ref<any[]>([])
const editOrderProductLoading = ref(false)
const selectedEditOrderProductRows = ref<any[]>([])

// 编辑订单分页数据
const editOrderPagination = reactive({
  pageIndex: 1,
  pageSize: 100,
  totalCount: 0,
  totalPage: 0
})

// 打印相关数据
const printDialogVisible = ref(false)
const printData = ref<any>(null)
const printProductDetails = ref<any[]>([])

// 列设置相关数据
const columnSettingsVisible = ref(false)
const columnConfigList = ref([
  { index: 1, prop: 'orderNo', label: '单据编号', visible: true, sortable: true, width: 220 },
  { index: 2, prop: 'remark', label: '备注', visible: true, sortable: false, width: 180 },
  { index: 3, prop: 'createTime', label: '创建时间', visible: true, sortable: true, width: 160 },
  { index: 4, prop: 'creator', label: '创建人', visible: true, sortable: false, width: 100 },
  { index: 5, prop: 'modifier', label: '修改人', visible: true, sortable: false, width: 100 },
  { index: 6, prop: 'modifyTime', label: '修改时间', visible: true, sortable: true, width: 160 }
])

// 保存原始列配置用于重置
const originalColumnConfig = ref([
  { index: 1, prop: 'orderNo', label: '单据编号', visible: true, sortable: true, width: 220 },
  { index: 2, prop: 'remark', label: '备注', visible: true, sortable: false, width: 180 },
  { index: 3, prop: 'createTime', label: '创建时间', visible: true, sortable: true, width: 160 },
  { index: 4, prop: 'creator', label: '创建人', visible: true, sortable: false, width: 100 },
  { index: 5, prop: 'modifier', label: '修改人', visible: true, sortable: false, width: 100 },
  { index: 6, prop: 'modifyTime', label: '修改时间', visible: true, sortable: true, width: 160 }
])

// 计算属性：获取可见的列
const visibleColumns = computed(() => {
  return columnConfigList.value.filter(column => column.visible)
})

// 获取销售订单列表
const getSalesOrderList = async () => {
  try {
    loading.value = true
    const response = await MES_SMH_ApiHost.post('/api/SalesOrder/GetPagedList', {
      orderNo: searchForm.orderNo || '',
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    })

    if (response.data.code === 200) {
      salesOrderList.value = response.data.pageData
      pagination.totalCount = response.data.totalCount
      pagination.totalPage = response.data.totalPage
      console.log('销售订单列表数据:', salesOrderList.value)
    } else {
      ElMessage.error(response.data.msg || '获取销售订单列表失败')
    }
  } catch (error) {
    console.error('获取销售订单列表失败:', error)
    ElMessage.error('获取销售订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取产品明细列表
const getProductDetailList = async (salesOrderId?: number) => {
  try {
    productLoading.value = true
    
    let response
    if (salesOrderId) {
      console.log('正在获取指定销售订单的产品明细，销售订单ID:', salesOrderId)
      response = await MES_SMH_ApiHost.get(`/api/SalesOrder/GetProductDetails/${salesOrderId}`)
    } else {
      console.log('正在获取所有产品明细数据')
      response = await MES_SMH_ApiHost.get('/api/SalesOrder/GetAllProductDetails')
    }
    
    console.log('API响应:', response.data)

    if (response.data.code === 200) {
      // 显示所有产品明细数据
      productDetailList.value = response.data.data || []
      console.log('产品明细数据(显示全部):', productDetailList.value)
      console.log('总数据条数:', productDetailList.value.length)
    } else {
      ElMessage.error(response.data.msg || '获取产品明细失败')
      productDetailList.value = []
    }
  } catch (error) {
    console.error('获取产品明细失败:', error)
    ElMessage.error('获取产品明细失败')
    productDetailList.value = []
  } finally {
    productLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  getSalesOrderList()
}

// 刷新
const handleRefresh = () => {
  getSalesOrderList()
  // 刷新时获取所有产品明细数据
  getProductDetailList()
}

// 列设置相关方法
const handleColumnSettings = () => {
  columnSettingsVisible.value = true
}

const handleColumnVisibilityChange = () => {
  // 列可见性变化时的处理逻辑
  console.log('列可见性变化:', columnConfigList.value)
}

const handleCloseColumnSettings = () => {
  columnSettingsVisible.value = false
  // 取消时恢复原始配置
  columnConfigList.value = JSON.parse(JSON.stringify(originalColumnConfig.value))
}

const handleResetColumnSettings = () => {
  // 重置为原始配置
  columnConfigList.value = JSON.parse(JSON.stringify(originalColumnConfig.value))
  ElMessage.success('列设置已重置')
}

const handleConfirmColumnSettings = () => {
  // 确认列设置
  originalColumnConfig.value = JSON.parse(JSON.stringify(columnConfigList.value))
  columnSettingsVisible.value = false
  ElMessage.success('列设置已保存')
}

// 拖拽相关方法
const dragStartIndex = ref(-1)

const handleDragStart = (index: number) => {
  dragStartIndex.value = index
}

const handleDrop = (dropIndex: number) => {
  if (dragStartIndex.value === -1 || dragStartIndex.value === dropIndex) {
    return
  }
  
  // 重新排序列配置
  const draggedItem = columnConfigList.value[dragStartIndex.value]
  const newList = [...columnConfigList.value]
  
  // 移除拖拽的项目
  newList.splice(dragStartIndex.value, 1)
  // 在目标位置插入
  newList.splice(dropIndex, 0, draggedItem)
  
  // 更新索引
  newList.forEach((item, index) => {
    item.index = index + 1
  })
  
  columnConfigList.value = newList
  dragStartIndex.value = -1
}

const handleRowDrop = () => {
  // Element Plus 表格的拖拽事件处理
  console.log('行拖拽完成')
}

const handleDragLeave = (index: number) => {
  // 移除拖拽目标样式
  const elements = document.querySelectorAll('.column-item')
  elements.forEach(el => el.classList.remove('drop-target'))
}

const handleDragEnter = (index: number) => {
  // 添加拖拽目标样式
  const elements = document.querySelectorAll('.column-item')
  elements.forEach(el => el.classList.remove('drop-target'))
  
  if (dragStartIndex.value !== index) {
    const targetElement = document.querySelector(`[data-index="${index}"]`) as HTMLElement
    if (targetElement) {
      targetElement.classList.add('drop-target')
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 产品表格选择变化
const handleProductSelectionChange = (selection: any[]) => {
  selectedProductRows.value = selection
}

// 行点击事件
const handleRowClick = (row: any) => {
  console.log('点击了销售订单行:', row)
  // 尝试多种可能的ID字段名
  const salesOrderId = row.salesOrderId || row.id || row.orderId
  console.log('使用的销售订单ID:', salesOrderId)
  
  if (salesOrderId) {
    currentSalesOrderId.value = salesOrderId
    // 点击销售订单行时，获取该销售订单的产品明细数据
    getProductDetailList(salesOrderId)
  } else {
    ElMessage.warning('无法获取销售订单ID')
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  getSalesOrderList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  getSalesOrderList()
}

// 新增销售订单
const handleAdd = () => {
  dialogVisible.value = true
  // 重置表单
  newOrderForm.orderNo = ''
  newOrderForm.remark = ''
  newOrderProductList.value = []
  selectedNewOrderProductRows.value = []
  newOrderPagination.pageIndex = 1
  newOrderPagination.totalCount = 0
}

// 编辑销售订单
const handleEdit = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要编辑的销售订单')
    return
  }
  if (selectedRows.value.length > 1) {
    ElMessage.warning('只能选择一个销售订单进行编辑')
    return
  }
  
  const selectedOrder = selectedRows.value[0]
  console.log('准备编辑销售订单:', selectedOrder)
  
  // 打开编辑弹窗
  editDialogVisible.value = true
  
  // 填充编辑表单数据
  editOrderForm.orderNo = selectedOrder.orderNo || ''
  editOrderForm.remark = selectedOrder.remark || ''
  editOrderForm.salesOrderId = selectedOrder.salesOrderId || selectedOrder.id
  
  // 清空产品列表
  editOrderProductList.value = []
  selectedEditOrderProductRows.value = []
  editOrderPagination.pageIndex = 1
  editOrderPagination.totalCount = 0
  
  // 获取该销售订单的产品明细
  if (editOrderForm.salesOrderId) {
    getEditOrderProductDetails(editOrderForm.salesOrderId)
  }
}

// 打印销售订单
const handlePrint = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要打印的销售订单')
    return
  }

  try {
    // 支持打印多条数据
    const selectedOrders = selectedRows.value
    const printOrders = []
    const allProductDetails = []

    // 获取所有选中订单的详细信息
    for (const order of selectedOrders) {
      const salesOrderId = order.salesOrderId || order.id || order.orderId
      
      try {
        // 获取销售订单详情
        const orderResponse = await MES_SMH_ApiHost.get(`/api/SalesOrder/GetDetail/${salesOrderId}`)
        if (orderResponse.data.code === 200) {
          printOrders.push(orderResponse.data.data)
        }

        // 获取产品明细
        const detailResponse = await MES_SMH_ApiHost.get(`/api/SalesOrder/GetProductDetails/${salesOrderId}`)
        if (detailResponse.data.code === 200) {
          const details = detailResponse.data.data || []
          allProductDetails.push(...details)
        }
             } catch (error) {
         console.error(`获取订单 ${salesOrderId} 信息失败:`, error)
         // 如果API调用失败，使用当前行的数据作为备选
         printOrders.push(order)
       }
    }

    if (printOrders.length === 0) {
      ElMessage.error('没有获取到有效的销售订单信息')
      return
    }

    // 设置打印数据
    printData.value = printOrders
    printProductDetails.value = allProductDetails
    printDialogVisible.value = true

    ElMessage.success(`准备打印 ${printOrders.length} 个销售订单`)

  } catch (error) {
    console.error('打印准备失败:', error)
    ElMessage.error('打印准备失败，请重试')
  }
}

// 打印预览
const handlePrintPreview = () => {
  // 打开浏览器打印预览
  window.print()
}

// 执行打印
const handlePrintExecute = () => {
  // 执行打印
  window.print()
}

// 关闭打印对话框
const handleClosePrintDialog = () => {
  printDialogVisible.value = false
  printData.value = null
  printProductDetails.value = []
}

// 导出模板
const handleExportTemplate = () => {
  try {
    // 创建模板数据（只有表头，没有实际数据）
    const templateData = [
      {
        '序号': 1,
        '单据编号': 'XSDD20250814194301647',
        '备注': '示例备注',
        '创建时间': '2025-08-14 19:43:02',
        '创建人': '超级管理员',
        '修改人': '超级管理员',
        '修改时间': '2025-08-14 19:43:02'
      }
    ]

    // 创建CSV内容
    const headers = ['序号', '单据编号', '备注', '创建时间', '创建人', '修改人', '修改时间']
    const csvContent = [
      headers.join(','),
      ...templateData.map(row => 
        headers.map(header => {
          const value = (row as any)[header] || ''
          // 确保值是字符串类型
          const stringValue = String(value)
          // 如果值包含逗号、引号或换行符，需要用引号包围
          if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
            return `"${stringValue.replace(/"/g, '""')}"`
          }
          return stringValue
        }).join(',')
      )
    ].join('\n')

    // 添加BOM以确保Excel正确识别中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `销售订单导入模板_${new Date().toISOString().slice(0, 10)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('成功导出销售订单导入模板')
  } catch (error) {
    console.error('导出模板失败:', error)
    ElMessage.error('导出模板失败，请重试')
  }
}

// 删除销售订单
const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的销售订单')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个销售订单吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const salesOrderIds = selectedRows.value.map(row => row.salesOrderId || row.id || row.orderId)
    const response = await MES_SMH_ApiHost.delete('/api/SalesOrder/BatchDelete', {
      data: { salesOrderIds }
    })

    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || '删除成功')
      getSalesOrderList()
      selectedRows.value = []
      // 如果删除的订单包含当前选中的订单，清空产品明细
      if (currentSalesOrderId.value && salesOrderIds.includes(currentSalesOrderId.value)) {
        currentSalesOrderId.value = null
        productDetailList.value = []
      }
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 导出销售订单
const handleExport = () => {
  try {
    // 准备导出数据
    const exportData = salesOrderList.value.map((item, index) => ({
      '序号': index + 1,
      '单据编号': item.orderNo || '',
      '备注': item.remark || '',
      '创建时间': item.createTime || '',
      '创建人': item.creator || '',
      '修改人': item.modifier || '',
      '修改时间': item.modifyTime || ''
    }))

    // 如果没有数据，提示用户
    if (exportData.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    // 创建CSV内容
    const headers = ['序号', '单据编号', '备注', '创建时间', '创建人', '修改人', '修改时间']
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => 
        headers.map(header => {
          const value = (row as any)[header] || ''
          // 确保值是字符串类型
          const stringValue = String(value)
          // 如果值包含逗号、引号或换行符，需要用引号包围
          if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
            return `"${stringValue.replace(/"/g, '""')}"`
          }
          return stringValue
        }).join(',')
      )
    ].join('\n')

    // 添加BOM以确保Excel正确识别中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `销售订单数据_${new Date().toISOString().slice(0, 10)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success(`成功导出 ${exportData.length} 条销售订单数据`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 显示所有产品明细
const handleShowAllProducts = () => {
  currentSalesOrderId.value = null
  getProductDetailList()
}



// 弹窗相关函数
const handleSelectProduct = () => {
  productSelectDialogVisible.value = true
  // 重置搜索表单
  productSearchForm.productCode = ''
  productSearchForm.productName = ''
  productSearchForm.productSpec = ''
  // 重置选择
  selectedProductSelectRows.value = []
  // 加载产品列表
  getProductSelectList()
}

const handleDeleteProductRow = () => {
  if (selectedNewOrderProductRows.value.length === 0) {
    ElMessage.warning('请选择要删除的产品行')
    return
  }
  
  const selectedIds = selectedNewOrderProductRows.value.map(row => row.id || row.productCode)
  newOrderProductList.value = newOrderProductList.value.filter(item => 
    !selectedIds.includes(item.id || item.productCode)
  )
  selectedNewOrderProductRows.value = []
  ElMessage.success('删除成功')
}

const handleImportProduct = () => {
  importDialogVisible.value = true
  selectedFile.value = null
}

// 导入相关函数
const handleSelectFile = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = (event) => {
    const target = event.target as HTMLInputElement
    if (target.files && target.files.length > 0) {
      const file = target.files[0]
      if (file.size > 100 * 1024 * 1024) { // 100MB
        ElMessage.error('文件大小不能超过100M')
        return
      }
      if (!file.name.match(/\.(xlsx|xls)$/i)) {
        ElMessage.error('只能上传Excel文件')
        return
      }
      selectedFile.value = file
    }
  }
  input.click()
}

const handleDownloadTemplate = () => {
  // 创建Excel模板数据 - 根据图二的列头
  const templateData = [
    ['产品编号', '产品名称', '产品规格', '工单编号', '数量', '完成数'],
    ['CP001', '示例产品1', '规格A', 'WO20231201001', '10', '0'],
    ['CP002', '示例产品2', '规格B', 'WO20231201002', '20', '0'],
    ['CP003', '示例产品3', '规格C', 'WO20231201003', '15', '0']
  ]
  
  // 生成CSV格式的数据
  const csvContent = templateData.map(row => row.join(',')).join('\n')
  
  // 添加BOM以确保Excel正确识别中文
  const BOM = '\uFEFF'
  const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
  
  // 创建下载链接
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '销售订单产品明细导入模板.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('模板下载成功')
}

const handleUploadFile = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  try {
    // 读取文件内容
    const reader = new FileReader()
    reader.onload = (event) => {
      const content = event.target?.result as string
      if (content) {
        // 解析CSV内容
        const lines = content.split('\n')
        const importedProducts: any[] = []
        
        // 跳过标题行，从第二行开始处理数据
        for (let i = 1; i < lines.length; i++) {
          const line = lines[i].trim()
          if (line) {
            const columns = line.split(',')
            if (columns.length >= 6) {
              const product = {
                productCode: columns[0]?.trim() || '',
                productName: columns[1]?.trim() || '',
                productSpec: columns[2]?.trim() || '',
                workOrderNo: columns[3]?.trim() || '',
                quantity: parseInt(columns[4]?.trim()) || 0,
                completedQty: parseInt(columns[5]?.trim()) || 0
              }
              
              // 验证必填字段
              if (product.productCode && product.productName && product.quantity > 0) {
                importedProducts.push(product)
              }
            }
          }
        }
        
        if (importedProducts.length > 0) {
          // 将导入的产品添加到弹窗中的产品明细列表
          importedProducts.forEach(product => {
            const newProductDetail = {
              salesOrderDetailId: Date.now() + Math.random(), // 临时ID
              salesOrderId: 0,
              productCode: product.productCode,
              productName: product.productName,
              productSpec: product.productSpec,
              workOrderNo: product.workOrderNo,
              unit: '个', // 默认单位
              quantity: product.quantity,
              completedQty: product.completedQty,
              createTime: new Date().toISOString(),
              creator: '当前用户',
              modifyTime: new Date().toISOString(),
              modifier: '当前用户'
            }
            newOrderProductList.value.push(newProductDetail)
          })
          
          ElMessage.success(`成功导入 ${importedProducts.length} 个产品`)
          importDialogVisible.value = false
          selectedFile.value = null
        } else {
          ElMessage.warning('文件中没有有效的数据，请检查文件格式')
        }
      }
    }
    
    reader.onerror = () => {
      ElMessage.error('文件读取失败')
    }
    
    // 读取文件内容
    reader.readAsText(selectedFile.value, 'utf-8')
    
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')
  }
}

const handleFileDrop = (event: DragEvent) => {
  event.preventDefault()
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    const file = files[0]
    if (file.size > 100 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过100M')
      return
    }
    if (!file.name.match(/\.(xlsx|xls)$/i)) {
      ElMessage.error('只能上传Excel文件')
      return
    }
    selectedFile.value = file
  }
}

const handleFileDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleFileDragLeave = (event: DragEvent) => {
  event.preventDefault()
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleCloseImport = () => {
  importDialogVisible.value = false
  selectedFile.value = null
}

const handleRefreshProduct = () => {
  ElMessage.info('刷新产品功能待实现')
}

const handleNewOrderProductSelectionChange = (selection: any[]) => {
  selectedNewOrderProductRows.value = selection
}

const handleNewOrderSizeChange = (size: number) => {
  newOrderPagination.pageSize = size
  newOrderPagination.pageIndex = 1
  // 这里可以重新加载产品数据
}

const handleNewOrderCurrentChange = (page: number) => {
  newOrderPagination.pageIndex = page
  // 这里可以重新加载产品数据
}

const handleSaveOrder = async () => {
  try {
    // 验证必填字段
    if (newOrderProductList.value.length === 0) {
      ElMessage.warning('请至少添加一个产品')
      return
    }

    // 验证产品数据
    for (const product of newOrderProductList.value) {
      if (!product.productCode || !product.productName || !product.quantity) {
        ElMessage.warning('请完善产品信息（产品编号、产品名称、数量为必填项）')
        return
      }
    }

    // 构建请求数据
    const requestData = {
      orderNo: newOrderForm.orderNo || '', // 如果为空，后端会自动生成
      remark: newOrderForm.remark || '',
      productDetails: newOrderProductList.value.map(product => ({
        productCode: product.productCode,
        productName: product.productName,
        productSpec: product.productSpec || '',
        workOrderNo: product.workOrderNo || '',
        quantity: product.quantity,
        completedQty: product.completedQty || 0
      }))
    }

    console.log('准备保存销售订单，数据:', requestData)

    // 调用后端API
    const response = await MES_SMH_ApiHost.post('/api/SalesOrder/Add', requestData)

    console.log('保存销售订单响应:', response.data)

    if (response.data.code === 200) {
      ElMessage.success('销售订单保存成功')
      // 关闭弹窗
      dialogVisible.value = false
      // 刷新销售订单列表
      getSalesOrderList()
      // 刷新产品明细列表
      getProductDetailList()
    } else {
      ElMessage.error(response.data.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存销售订单失败:', error)
    ElMessage.error('保存销售订单失败')
  }
}

const handleCloseDialog = () => {
  dialogVisible.value = false
}

// 产品选择相关函数
const getProductSelectList = async () => {
  try {
    productSelectLoading.value = true
    
    // 调用后端获取所有产品明细数据
    const response = await MES_SMH_ApiHost.get('/api/SalesOrder/GetAllProductDetails', {
      params: {
        productCode: productSearchForm.productCode || '',
        productName: productSearchForm.productName || '',
        productSpec: productSearchForm.productSpec || '',
        pageIndex: productSelectPagination.pageIndex,
        pageSize: productSelectPagination.pageSize
      }
    })
    
    console.log('产品选择API响应:', response.data)
    
    if (response.data.code === 200) {
      const data = response.data.data || []
      
      // 直接使用后端返回的产品数据，不再需要去重处理
      const products = data.map((item: any) => ({
        id: item.salesOrderDetailId, // 使用产品ID作为临时ID
        productCode: item.productCode,
        productName: item.productName,
        productSpec: item.productSpec,
        unit: item.unit || '个', // 使用后端返回的库存单位，如果没有则默认为'个'
        stockQty: item.stockQty || 0, // 使用后端返回的库存数量，如果没有则默认为0
        price: item.price || 0, // 使用后端返回的单价，如果没有则默认为0
        createTime: item.createTime
      }))
      
      productSelectList.value = products
      productSelectPagination.totalCount = products.length
      productSelectPagination.totalPage = Math.ceil(products.length / productSelectPagination.pageSize)
      
      console.log('处理后的产品选择数据:', products)
    } else {
      ElMessage.error(response.data.msg || '获取产品列表失败')
      productSelectList.value = []
      productSelectPagination.totalCount = 0
      productSelectPagination.totalPage = 0
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
    productSelectList.value = []
    productSelectPagination.totalCount = 0
    productSelectPagination.totalPage = 0
  } finally {
    productSelectLoading.value = false
  }
}

const handleProductSearch = () => {
  productSelectPagination.pageIndex = 1
  getProductSelectList()
}

const handleProductSearchReset = () => {
  productSearchForm.productCode = ''
  productSearchForm.productName = ''
  productSearchForm.productSpec = ''
  productSelectPagination.pageIndex = 1
  getProductSelectList()
}

const handleProductSelectChange = (selection: any[]) => {
  selectedProductSelectRows.value = selection
}

const handleProductSelectSizeChange = (size: number) => {
  productSelectPagination.pageSize = size
  productSelectPagination.pageIndex = 1
  getProductSelectList()
}

const handleProductSelectCurrentChange = (page: number) => {
  productSelectPagination.pageIndex = page
  getProductSelectList()
}

const handleConfirmProductSelect = () => {
  if (selectedProductSelectRows.value.length === 0) {
    ElMessage.warning('请选择要添加的产品')
    return
  }
  
  const selectedCount = selectedProductSelectRows.value.length
  
  // 判断当前是新建模式还是编辑模式
  if (dialogVisible.value) {
    // 新建模式：添加到新建订单的产品列表中
    selectedProductSelectRows.value.forEach(product => {
      const newProduct = {
        ...product,
        quantity: 1, // 默认数量为1
        completedQty: 0,
        workOrderNo: '',
        creator: '当前用户',
        createTime: new Date().toISOString()
      }
      newOrderProductList.value.push(newProduct)
    })
    
    // 更新分页数据
    newOrderPagination.totalCount = newOrderProductList.value.length
  } else if (editDialogVisible.value) {
    // 编辑模式：添加到编辑订单的产品列表中
    selectedProductSelectRows.value.forEach(product => {
      const newProduct = {
        ...product,
        quantity: 1, // 默认数量为1
        completedQty: 0,
        workOrderNo: '',
        creator: '当前用户',
        createTime: new Date().toISOString()
      }
      editOrderProductList.value.push(newProduct)
    })
    
    // 更新分页数据
    editOrderPagination.totalCount = editOrderProductList.value.length
  }
  
  // 关闭产品选择弹窗
  productSelectDialogVisible.value = false
  selectedProductSelectRows.value = []
  
  ElMessage.success(`成功添加 ${selectedCount} 个产品`)
}

const handleCloseProductSelectDialog = () => {
  productSelectDialogVisible.value = false
  selectedProductSelectRows.value = []
}

// 编辑相关函数
const getEditOrderProductDetails = async (salesOrderId: number) => {
  try {
    editOrderProductLoading.value = true
    const response = await MES_SMH_ApiHost.get(`/api/SalesOrder/GetProductDetails/${salesOrderId}`)
    
    if (response.data.code === 200) {
      editOrderProductList.value = response.data.data || []
      editOrderPagination.totalCount = editOrderProductList.value.length
      console.log('编辑订单产品明细数据:', editOrderProductList.value)
    } else {
      ElMessage.error(response.data.msg || '获取产品明细失败')
      editOrderProductList.value = []
    }
  } catch (error) {
    console.error('获取编辑订单产品明细失败:', error)
    ElMessage.error('获取产品明细失败')
    editOrderProductList.value = []
  } finally {
    editOrderProductLoading.value = false
  }
}

const handleEditSelectProduct = () => {
  productSelectDialogVisible.value = true
  // 重置搜索表单
  productSearchForm.productCode = ''
  productSearchForm.productName = ''
  productSearchForm.productSpec = ''
  // 重置选择
  selectedProductSelectRows.value = []
  // 加载产品列表
  getProductSelectList()
}

const handleEditDeleteProductRow = () => {
  if (selectedEditOrderProductRows.value.length === 0) {
    ElMessage.warning('请选择要删除的产品行')
    return
  }
  
  const selectedIds = selectedEditOrderProductRows.value.map(row => row.salesOrderDetailId || row.id || row.productCode)
  editOrderProductList.value = editOrderProductList.value.filter(item => 
    !selectedIds.includes(item.salesOrderDetailId || item.id || item.productCode)
  )
  selectedEditOrderProductRows.value = []
  ElMessage.success('删除成功')
}

const handleEditImportProduct = () => {
  ElMessage.info('导入产品功能待实现')
}

const handleEditRefreshProduct = () => {
  if (editOrderForm.salesOrderId) {
    getEditOrderProductDetails(editOrderForm.salesOrderId)
  }
}

const handleEditOrderProductSelectionChange = (selection: any[]) => {
  selectedEditOrderProductRows.value = selection
}

const handleEditOrderSizeChange = (size: number) => {
  editOrderPagination.pageSize = size
  editOrderPagination.pageIndex = 1
}

const handleEditOrderCurrentChange = (page: number) => {
  editOrderPagination.pageIndex = page
}

const handleSaveEditOrder = async () => {
  try {
    // 验证必填字段
    if (editOrderProductList.value.length === 0) {
      ElMessage.warning('请至少添加一个产品')
      return
    }

    // 验证产品数据
    for (const product of editOrderProductList.value) {
      if (!product.productCode || !product.productName || !product.quantity) {
        ElMessage.warning('请完善产品信息（产品编号、产品名称、数量为必填项）')
        return
      }
    }

    // 构建请求数据
    const requestData = {
      salesOrderId: editOrderForm.salesOrderId,
      orderNo: editOrderForm.orderNo,
      remark: editOrderForm.remark || '',
      productDetails: editOrderProductList.value.map(product => ({
        salesOrderDetailId: product.salesOrderDetailId,
        productCode: product.productCode,
        productName: product.productName,
        productSpec: product.productSpec || '',
        workOrderNo: product.workOrderNo || '',
        quantity: product.quantity,
        completedQty: product.completedQty || 0
      }))
    }

    console.log('准备保存编辑销售订单，数据:', requestData)

    // 调用后端API
    const response = await MES_SMH_ApiHost.put('/api/SalesOrder/Edit', requestData)

    console.log('保存编辑销售订单响应:', response.data)

    if (response.data.code === 200) {
      ElMessage.success('销售订单编辑成功')
      // 关闭弹窗
      editDialogVisible.value = false
      // 刷新销售订单列表
      getSalesOrderList()
      // 刷新产品明细列表
      getProductDetailList()
    } else {
      ElMessage.error(response.data.msg || '编辑失败')
    }
  } catch (error) {
    console.error('编辑销售订单失败:', error)
    ElMessage.error('编辑销售订单失败')
  }
}

const handleCloseEditDialog = () => {
  editDialogVisible.value = false
}

// 页面加载时获取数据
onMounted(() => {
  getSalesOrderList()
  // 页面加载时获取所有产品明细数据
  getProductDetailList()
})
</script>

<style scoped>
.sales-order-container {
  padding: 16px;
  background-color: #f0f2f5;
  min-height: 100vh;
  height: 100vh;
  overflow-y: auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.sales-order-section,
.product-detail-section {
  background-color: white;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fafafa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  color: #262626;
  font-size: 14px;
  font-weight: 500;
  line-height: 1.4;
}

.section-actions {
  display: flex;
  gap: 8px;
}

.search-action-bar {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fafafa;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-area .el-input {
  width: 200px;
}

.search-area .el-input :deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  box-shadow: none;
}

.search-area .el-input :deep(.el-input__wrapper:hover) {
  border-color: #40a9ff;
}

.search-area .el-input :deep(.el-input__wrapper.is-focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  border-radius: 4px;
  font-size: 12px;
  padding: 4px 12px;
  height: 28px;
  line-height: 1.4;
}

.action-buttons .el-button--success {
  background-color: #52c41a;
  border-color: #52c41a;
  color: white;
}

.action-buttons .el-button--success:hover {
  background-color: #73d13d;
  border-color: #73d13d;
}

.action-buttons .el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
  color: white;
}

.action-buttons .el-button--primary:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.action-buttons .el-button--warning {
  background-color: #faad14;
  border-color: #faad14;
  color: white;
}

.action-buttons .el-button--warning:hover {
  background-color: #ffc53d;
  border-color: #ffc53d;
}

.action-buttons .el-button--danger {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  color: white;
}

.action-buttons .el-button--danger:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.action-buttons .el-button--info {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #595959;
}

.action-buttons .el-button--info:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.table-container {
  padding: 0;
}

/* 产品明细表格样式 - 显示所有数据，支持滚动 */
.product-detail-section .table-container {
  max-height: 700px;
  overflow-y: auto;
}

/* 产品明细表格固定高度，确保滚动功能 */
.product-detail-section .table-container :deep(.el-table) {
  max-height: 700px;
}

/* 产品明细表格行高设置 */
.product-detail-section .table-container :deep(.el-table__body tr) {
  height: 40px;
}

/* 确保表格底部有足够空间显示最后一行 */
.product-detail-section .table-container :deep(.el-table__body-wrapper) {
  padding-bottom: 60px;
}

/* 确保表格容器底部有足够空间 */
.product-detail-section .table-container {
  padding-bottom: 10px;
}

/* 打印预览弹窗样式 */
.print-preview-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.print-preview-content {
  background: white;
  padding: 30px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 打印头部样式 */
.print-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #409eff;
}

.company-logo .logo-circle {
  width: 60px;
  height: 60px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
}

.print-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.qr-code .qr-placeholder {
  width: 80px;
  height: 80px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

/* 订单信息样式 */
.order-info {
  margin-bottom: 30px;
}

.order-section {
  margin-bottom: 20px;
}

.order-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.order-header h4 {
  color: #409eff;
  margin: 0;
  font-size: 16px;
}

.order-divider {
  height: 1px;
  background: #eee;
  margin: 20px 0;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
  line-height: 1.6;
}

.info-label {
  font-weight: bold;
  width: 100px;
  color: #333;
}

.info-value {
  color: #666;
  flex: 1;
}

/* 产品明细表格样式 */
.product-detail-table {
  margin-bottom: 30px;
}

.print-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ddd;
}

.print-table th,
.print-table td {
  border: 1px solid #ddd;
  padding: 12px 8px;
  text-align: center;
}

.print-table th {
  background: #f5f5f5;
  font-weight: bold;
  color: #333;
}

.print-table td {
  color: #666;
}

/* 打印底部样式 */
.print-footer {
  text-align: center;
  color: #999;
  font-size: 14px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

/* 打印样式 */
@media print {
  .print-preview-dialog :deep(.el-dialog__header),
  .print-preview-dialog :deep(.el-dialog__footer) {
    display: none !important;
  }
  
  .print-preview-dialog :deep(.el-dialog) {
    position: static !important;
    margin: 0 !important;
    width: 100% !important;
    max-width: none !important;
  }
  
  .print-preview-dialog :deep(.el-dialog__body) {
    padding: 0 !important;
    max-height: none !important;
    overflow: visible !important;
  }
  
  .print-preview-content {
    box-shadow: none !important;
    border: none !important;
  }
}

.table-container :deep(.el-table) {
  border: none;
}

.table-container :deep(.el-table__header-wrapper) {
  background-color: #fafafa;
}

.table-container :deep(.el-table th) {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  color: #262626;
  font-weight: 500;
  font-size: 12px;
  padding: 8px 0;
}

.table-container :deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 8px 0;
  font-size: 12px;
  color: #595959;
}

.table-container :deep(.el-table--border) {
  border: 1px solid #e8e8e8;
}

.table-container :deep(.el-table__row:hover) {
  background-color: #f5f5f5;
}

.table-container :deep(.el-table__row--striped) {
  background-color: #fafafa;
}

.table-container :deep(.el-table__row--striped:hover) {
  background-color: #f0f0f0;
}

/* 表格行点击效果 */
.sales-order-section .table-container :deep(.el-table__row) {
  cursor: pointer;
}

.sales-order-section .table-container :deep(.el-table__row:hover) {
  background-color: #e6f7ff !important;
}

.sales-order-section .table-container :deep(.el-table__row.current-row) {
  background-color: #e6f7ff !important;
}

/* 产品明细表格样式 */
.product-detail-section .table-container :deep(.el-table__row) {
  cursor: default;
}

.product-detail-section .table-container :deep(.el-table__row:hover) {
  background-color: #f5f5f5 !important;
}

.pagination-container {
  padding: 12px 16px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e8e8e8;
  background-color: #fafafa;
}

.pagination-container :deep(.el-pagination) {
  font-size: 12px;
  color: #595959;
}

.pagination-container :deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
  min-width: 28px;
  height: 28px;
  line-height: 28px;
  font-size: 12px;
}

.pagination-container :deep(.el-pagination .el-pager li.is-active) {
  background-color: #1890ff;
  color: white;
}

.pagination-container :deep(.el-pagination .btn-prev),
.pagination-container :deep(.el-pagination .btn-next) {
  border-radius: 4px;
  margin: 0 2px;
  min-width: 28px;
  height: 28px;
  line-height: 28px;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes) {
  margin-right: 16px;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes .el-select) {
  width: 100px;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes .el-select .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  box-shadow: none;
}

.pagination-container :deep(.el-pagination .el-pagination__jump) {
  margin-left: 16px;
}

.pagination-container :deep(.el-pagination .el-pagination__jump .el-input) {
  width: 50px;
  margin: 0 8px;
}

.pagination-container :deep(.el-pagination .el-pagination__jump .el-input .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  box-shadow: none;
}

/* 必填字段标记 */
.table-container :deep(.el-table th) {
  position: relative;
}

.table-container :deep(.el-table th[data-required="true"]::before) {
  content: "*";
  color: #ff4d4f;
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-action-bar {
    flex-direction: column;
    gap: 12px;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .search-area .el-input {
    width: 100%;
  }
  
  .section-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

/* 弹窗样式 */
.sales-order-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.dialog-content {
  padding: 20px;
}

.order-info-section {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #262626;
  font-size: 14px;
}

.hint-banner {
  background-color: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #d46b08;
  font-size: 14px;
}

.hint-banner .el-icon {
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e8e8e8;
  background-color: #fafafa;
}

.dialog-footer .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 弹窗内产品明细表格样式 */
.sales-order-dialog .product-detail-section {
  margin-bottom: 0;
  border: none;
  box-shadow: none;
}

.sales-order-dialog .section-header {
  background-color: #f5f5f5;
  border-bottom: 1px solid #d9d9d9;
}

.sales-order-dialog .section-header h3 {
  color: #1890ff;
  font-weight: 600;
}

.sales-order-dialog .table-container {
  max-height: 400px;
  overflow-y: auto;
}

.sales-order-dialog .pagination-container {
  background-color: #fafafa;
  border-top: 1px solid #e8e8e8;
}

/* 列设置弹窗样式 */
.column-settings-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.column-settings-content {
  padding: 20px;
}

.settings-hint {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #52c41a;
  font-size: 14px;
}

.settings-hint .el-icon {
  font-size: 16px;
}

.column-config-table {
  margin-bottom: 20px;
}

.column-config-table :deep(.el-table) {
  border: 1px solid #e8e8e8;
}

.column-config-table :deep(.el-table__header-wrapper) {
  background-color: #fafafa;
}

.column-config-table :deep(.el-table th) {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  color: #262626;
  font-weight: 500;
  font-size: 12px;
  padding: 8px 0;
}

.column-config-table :deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 8px 0;
  font-size: 12px;
  color: #595959;
}

.column-config-table :deep(.el-table__row:hover) {
  background-color: #f5f5f5;
}

.column-config-table :deep(.el-table__row--striped) {
  background-color: #fafafa;
}

.column-config-table :deep(.el-table__row--striped:hover) {
  background-color: #f0f0f0;
}

/* 拖拽相关样式 */
.column-list {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

.column-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: white;
  cursor: move;
  transition: all 0.2s ease;
}

.column-item:last-child {
  border-bottom: none;
}

.column-item:hover {
  background-color: #f5f5f5;
}

.column-item.dragging {
  opacity: 0.5;
  background-color: #e6f7ff !important;
}

.column-item.drop-target {
  background-color: #f0f9ff !important;
  border-top: 2px solid #409eff;
}

.column-content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 16px;
}

.column-index {
  width: 60px;
  text-align: center;
  font-weight: 500;
  color: #666;
}

.column-name {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
}

.drag-handle {
  color: #999;
  font-size: 14px;
  cursor: move;
}

.column-item:hover .drag-handle {
  color: #409eff;
}

.column-visible {
  width: 100px;
  text-align: center;
}

/* 产品选择弹窗样式 */
.product-select-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.product-select-dialog .dialog-content {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.search-row {
  display: flex;
  gap: 16px;
  align-items: flex-end;
  flex-wrap: wrap;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 150px;
}

.search-item label {
  font-weight: 500;
  color: #262626;
  font-size: 14px;
}

.search-item .el-input {
  width: 200px;
}

.search-item .el-button {
  margin-right: 8px;
}

.product-table-section {
  margin-bottom: 20px;
}

.product-table-section :deep(.el-table) {
  border: 1px solid #e8e8e8;
}

.product-table-section :deep(.el-table__header-wrapper) {
  background-color: #fafafa;
}

.product-table-section :deep(.el-table th) {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  color: #262626;
  font-weight: 500;
  font-size: 12px;
  padding: 8px 0;
}

.product-table-section :deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 8px 0;
  font-size: 12px;
  color: #595959;
}

.product-table-section :deep(.el-table__row:hover) {
  background-color: #f5f5f5;
}

.product-table-section :deep(.el-table__row--striped) {
  background-color: #fafafa;
}

.product-table-section :deep(.el-table__row--striped:hover) {
  background-color: #f0f0f0;
}

/* 导入弹窗样式 */
.import-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.import-content {
  padding: 20px;
}

.import-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.upload-notice {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  background-color: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
}

.upload-notice .el-icon {
  color: #d46b08;
  font-size: 16px;
  margin-top: 2px;
}

.notice-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.notice-title {
  font-weight: 600;
  color: #262626;
  font-size: 14px;
}

.notice-text {
  color: #8c8c8c;
  font-size: 12px;
}

.file-drop-zone {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}

.file-drop-zone:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.drop-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #8c8c8c;
}

.upload-icon {
  font-size: 48px;
  color: #d9d9d9;
}

.drop-placeholder p {
  margin: 0;
  font-size: 14px;
}

.selected-file {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #262626;
}

.file-icon {
  font-size: 24px;
  color: #52c41a;
}

.file-name {
  font-weight: 500;
  font-size: 14px;
}

.file-size {
  color: #8c8c8c;
  font-size: 12px;
}
</style>
